package codingforgreat.lchot150;

public class Lc116 {
    class Node {
        public int val;
        public Node left;
        public Node right;
        public Node next;

        public Node() {
        }

        public Node(int _val) {
            val = _val;
        }

        public Node(int _val, Node _left, Node _right, Node _next) {
            val = _val;
            left = _left;
            right = _right;
            next = _next;
        }

        public class MyQueue {
            public Node head;
            public Node tail;
            public int size;

            public MyQueue() {
                head = null;
                tail = null;
                size = 0;
            }

            public boolean isEmpty() {
                return size == 0;
            }

            public void push(Node node) {
                size++;
                if (head == null) {
                    head = node;
                    tail = node;
                } else {
                    tail.next = node;
                    tail = node;
                }
            }

            public Node poll() {
                size--;
                Node res = head;
                head = head.next;
                res.next = null;
                return res;
            }
        }

        public Node connect(Node root) {
            if (root == null) {
                return null;
            }
            MyQueue queue = new MyQueue();
            queue.push(root);
            while (!queue.isEmpty()) {
                int size = queue.size;
                Node pre = null;
                for (int i = 0; i < size; i++) {
                    Node cur = queue.poll();
                    if (cur.left != null) {
                        queue.push(cur.left);
                    }
                    if (cur.right != null) {
                        queue.push(cur.right);
                    }
                    if (pre != null) {
                        pre.next = cur;
                    }
                    pre = cur;
                }
            }
            return root;
        }
    }
}
